/*
 * @Description: 
 * @Author: Binggan
 * @Date: 2019-03-19 10:54:49
 * @LastEditors: Binggan
 * @LastEditTime: 2020-03-02 20:46:26
 */
import axios from 'axios'
import qs from 'qs'
import {Message} from 'iview';
// 添加请求拦截器

// axios.defaults.timeout = 8000;// 超时时间
// axios.defaults.baseURL = "http://qdeiqm.natappfree.cc";
axios.defaults.baseURL = process.env.API_ROOT;
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
// var loadinginstace = null;
axios.interceptors.request.use(config => {
    //loadinginstace = Loading.service({ fullscreen: true });// element ui Loading方法
    console.log("拦截前",config)
    // if (config.method != 'get') {
    //     config.data = qs.stringify(config.data);
    // }
    /* if(config.method === 'get'){
        //如果是get请求，且params是数组类型如arr=[1,2]，则转换成arr=1&arr=2
        config.paramsSerializer = function(params) {
            return qs.stringify(params, {arrayFormat: 'repeat'})
        }
    } */
    console.log("拦截后",config.data)
    //增加时间戳
    config.params = {
        _t: Date.parse(new Date())/1000,
        ...config.params
    }
    // let token = window.sessionStorage.getItem("TOKEN");
    // if(token) {
    //     config.headers.common['Authorization'] = "Bearer " + token;
    // }
    return config;
}, (error) => {
    //loadinginstace.close();
    Message.error({
        content: '请求超时',
        duration: 10,
        closable: true
    });
    return Promise.reject(error)
})
// 添加响应拦截器
axios.interceptors.response.use((response)=> {
    //loadinginstace.close()
    // 对响应数据做点什么
    let res=response.data;
    if(res.errorCode!=0){
        Message.error({
            content: res.errorMsg,
            duration: 3,
            closable: true
        });
        return res;
    }else if(res&&res.errorCode==0){
        return res;
    }
}, (error) => {
    console.log(error)
    let errorTip=['网络错误',"请求错误","未授权，请联系管理员","拒绝访问","请求地址出错","请求超时","服务器内部错误⊙﹏⊙∥"],index=0;
    if (error && error.response) {
        switch (error.response.status) {
            case 400:
                index = 1;
                break
            case 401:
                index = 2;
                break
            case 403:
                index = 3;
                break
            case 404:
                index = 4;
                errorTip[index]+=error.response.config.url;
                break
            case 408:
                index = 5;
                break
            case 500:
                index = 6;
                break;
        }
    }
    Message.error({
        content: errorTip[index],
        duration: 3,
        closable: true
    });
    return Promise.reject(error);
    // return Promise.reject(error);
});

export default axios